package com.bosssoft.platform.fasttcc.assist;

import com.bosssoft.platform.fasttcc.TccInvoke;
import com.bosssoft.platform.fasttcc.TccTransaction;
import com.bosssoft.platform.fasttcc.Xid;
import com.jfireframework.baseutil.StringUtil;
import com.bosssoft.platform.fasttcc.TccTransactionManager;

import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

public class TccConnection implements Connection
{
    public static ThreadLocal<TccInvoke> localTccInvoke = new ThreadLocal<>();
    private       Connection             physicalConn;
    private       TccTransactionManager  tccTransactionManager;

    public TccConnection(Connection physicalConn, TccTransactionManager tccTransactionManager)
    {
        this.physicalConn = physicalConn;
        this.tccTransactionManager = tccTransactionManager;
    }

    @Override
    public Statement createStatement() throws SQLException
    {
        return physicalConn.createStatement();
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException
    {
        return physicalConn.prepareStatement(sql);
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException
    {
        return physicalConn.prepareCall(sql);
    }

    @Override
    public String nativeSQL(String sql) throws SQLException
    {
        return physicalConn.nativeSQL(sql);
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException
    {
        physicalConn.setAutoCommit(autoCommit);
    }

    @Override
    public boolean getAutoCommit() throws SQLException
    {
        return physicalConn.getAutoCommit();
    }

    @Override
    public void commit() throws SQLException
    {
        TccInvoke tccInvoke = localTccInvoke.get();
        if (tccInvoke != null)
        {
            Xid completeStageXid = tccInvoke.getCompleteStageXid();
            insertTccLogAndCommit(completeStageXid, tccTransactionManager.getIdentifier());
            return;
        }
        TccTransaction currentTccTransaction = tccTransactionManager.getCurrentTccTransaction();
        if (currentTccTransaction != null && currentTccTransaction.getCurrentLocalTransactionXid() != null)
        {
            Xid xid = currentTccTransaction.getCurrentLocalTransactionXid();
            insertTccLogAndCommit(xid, tccTransactionManager.getIdentifier());
            return;
        }
        else
        {
            physicalConn.commit();
        }
    }

    private void insertTccLogAndCommit(Xid xid, String identifier) throws SQLException
    {
        String globalId = StringUtil.toHexString(xid.getGlobalId());
        String branchId = StringUtil.toHexString(xid.getBranchId());
        try (PreparedStatement preparedStatement = physicalConn.prepareStatement("insert into fasttcc (global_id,branch_id,create_time,identifier) value (?,?,?,?)"))
        {
            preparedStatement.setString(1, globalId);
            preparedStatement.setString(2, branchId);
            preparedStatement.setLong(3, System.currentTimeMillis());
            preparedStatement.setString(4, identifier);
            preparedStatement.executeUpdate();
        }
        physicalConn.commit();
    }

    @Override
    public void rollback() throws SQLException
    {
        physicalConn.rollback();
    }

    @Override
    public void close() throws SQLException
    {
        physicalConn.close();
    }

    @Override
    public boolean isClosed() throws SQLException
    {
        return physicalConn.isClosed();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException
    {
        return physicalConn.getMetaData();
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException
    {
        physicalConn.setReadOnly(readOnly);
    }

    @Override
    public boolean isReadOnly() throws SQLException
    {
        return physicalConn.isReadOnly();
    }

    @Override
    public void setCatalog(String catalog) throws SQLException
    {
        physicalConn.setCatalog(catalog);
    }

    @Override
    public String getCatalog() throws SQLException
    {
        return physicalConn.getCatalog();
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException
    {
        physicalConn.setTransactionIsolation(level);
    }

    @Override
    public int getTransactionIsolation() throws SQLException
    {
        return physicalConn.getTransactionIsolation();
    }

    @Override
    public SQLWarning getWarnings() throws SQLException
    {
        return physicalConn.getWarnings();
    }

    @Override
    public void clearWarnings() throws SQLException
    {
        physicalConn.clearWarnings();
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
    {
        return physicalConn.createStatement(resultSetType, resultSetConcurrency);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
    {
        return physicalConn.prepareStatement(sql, resultSetType, resultSetConcurrency);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
    {
        return physicalConn.prepareCall(sql, resultSetType, resultSetConcurrency);
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException
    {
        return physicalConn.getTypeMap();
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException
    {
        physicalConn.setTypeMap(map);
    }

    @Override
    public void setHoldability(int holdability) throws SQLException
    {
        physicalConn.setHoldability(holdability);
    }

    @Override
    public int getHoldability() throws SQLException
    {
        return physicalConn.getHoldability();
    }

    @Override
    public Savepoint setSavepoint() throws SQLException
    {
        return physicalConn.setSavepoint();
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException
    {
        return physicalConn.setSavepoint(name);
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException
    {
        physicalConn.rollback();
    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException
    {
        physicalConn.releaseSavepoint(savepoint);
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
    {
        return physicalConn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
    {
        return physicalConn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
    {
        return physicalConn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
    {
        return physicalConn.prepareStatement(sql, autoGeneratedKeys);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
    {
        return physicalConn.prepareStatement(sql, columnIndexes);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
    {
        return physicalConn.prepareStatement(sql, columnNames);
    }

    @Override
    public Clob createClob() throws SQLException
    {
        return physicalConn.createClob();
    }

    @Override
    public Blob createBlob() throws SQLException
    {
        return physicalConn.createBlob();
    }

    @Override
    public NClob createNClob() throws SQLException
    {
        return physicalConn.createNClob();
    }

    @Override
    public SQLXML createSQLXML() throws SQLException
    {
        return physicalConn.createSQLXML();
    }

    @Override
    public boolean isValid(int timeout) throws SQLException
    {
        return physicalConn.isValid(timeout);
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException
    {
        physicalConn.setClientInfo(name, value);
    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException
    {
        physicalConn.setClientInfo(properties);
    }

    @Override
    public String getClientInfo(String name) throws SQLException
    {
        return physicalConn.getClientInfo(name);
    }

    @Override
    public Properties getClientInfo() throws SQLException
    {
        return physicalConn.getClientInfo();
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException
    {
        return physicalConn.createArrayOf(typeName, elements);
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException
    {
        return physicalConn.createStruct(typeName, attributes);
    }

    @Override
    public void setSchema(String schema) throws SQLException
    {
        physicalConn.setSchema(schema);
    }

    @Override
    public String getSchema() throws SQLException
    {
        return physicalConn.getSchema();
    }

    @Override
    public void abort(Executor executor) throws SQLException
    {
        physicalConn.abort(executor);
    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException
    {
        physicalConn.setNetworkTimeout(executor, milliseconds);
    }

    @Override
    public int getNetworkTimeout() throws SQLException
    {
        return physicalConn.getNetworkTimeout();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException
    {
        return physicalConn.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException
    {
        return physicalConn.isWrapperFor(iface);
    }
}
